package ThreadDemo;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-16
 * Time: 14:34
 */
class CountTest{
    public static int getCount() {
        return count;
    }

    public static void setCount() {
        synchronized (Object.class){
            count++;
        }
    }

    private static int count = 0;
}
//死锁的第二种情况：两个线程，两把锁，每个线程各获得一把锁，并在各自的锁里尝试取获取对方的锁
public class DeadLockDemo1 {
    public static void main(String[] args) throws InterruptedException {
        Object o = new Object();
        Thread thread = new Thread(() -> {
            synchronized (Object.class){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o){//尝试取获取对方的锁
                    CountTest.setCount();
                }
            }

        });

        Thread thread2 = new Thread(() -> {
            synchronized (o){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (Object.class){//尝试取获取对方的锁
                    CountTest.setCount();
                }
            }
        });

        thread.start();
        thread2.start();
        thread.join();
        thread2.join();
        System.out.println(CountTest.getCount());

    }
}


